package cn.lisens.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class CustomInterceptor implements HandlerInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		logger.info("Interceptor - 请求前: {}", request.getRequestURI());
		
		// 如果不是HandlerMethod，直接放行（比如静态资源）
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查方法上是否有权限注解
//        RequiredPermission requiredPermission = method.getAnnotation(RequiredPermission.class);
//        if (requiredPermission == null) {
//            // 如果没有权限注解，直接放行
//            return true;
//        }
        
		request.getHeader("Token");
		String flag = request.getParameter("flag");
		if(!"1".equals(flag)) {
			sendErrorResponse(response, "无权限", HttpStatus.UNAUTHORIZED);
			return false;
		}
        // 可以在这里进行权限验证等操作
        // 返回true继续执行，返回false中断请求
        return "1".equals(flag);
	}
	
	/**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, String message, HttpStatus status) throws IOException {
        response.setStatus(status.value());
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", status.value());
        result.put("message", message);
        result.put("timestamp", System.currentTimeMillis());
        
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        response.getWriter().flush();
    }
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		logger.info("Interceptor - 请求处理完毕，视图渲染前"+handler.toString());
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		logger.info("Interceptor - 请求完成，视图渲染后");
	}
}
